<?php
if(empty($buid)&&empty($_GET['type']))
msg($config['weburl']."/login.php?forward=".urlencode("$config[weburl]/?m=product&s=shop_order"));
else
{
	if(!empty($buid))
	{
		if($_POST['act'] != 'order'){


			include_once("$config[webroot]/module/member/includes/plugin_orderadder_class.php");
			include_once("$config[webroot]/module/logistics/includes/logistics_class.php");
			include_once("$config[webroot]/module/member/includes/plugin_member_class.php");
			$orderadder=new orderadder();$logistics = new logistics(); $member=new member();
			$product_list = $_POST['item'];
			$product_pid = $_POST['pid'];
			$product_num = $_POST['num'];
            $spot_id =  !empty($_POST['spot']) ? $_POST['spot'] : '';//场馆
			$seat =  !empty($_POST['seat']) ? $_POST['seat'] : []; //座位
			$price =  !empty($_POST['price']) ? $_POST['price'] : []; //价格
			//判断是否是电子票is_electronic_ticket
			$esql = "select * from ".PRO." where id = '$product_pid' ";
			$db->query($esql);
			$parent_product = $db->fetchRow();
			$tpl->assign('parent_product',$parent_product);

			//积分
			$points=$member->get_points();
			$tpl->assign("points",round($points/100,2));
			foreach($price as $key => $val){
				$new_seat[$val][$key] = $seat[$key]; //价格对应
			}

			if(empty($product_list)){
				msg($config['weburl']."/index.php","您提交的票品为空，请重新下单购买");
				return false;
			}
			$total_price = 0;
			foreach($product_list as $key => $val){
				//选择的票品 查询详细信息 判断库存是否足够
				$explode = explode(",",$val);
				$sql = "select * from ".SETMEAL." where pid = '$product_pid' and performance_start_time = '{$explode[0]}' and price = '{$explode[1]}' ";
				$db->query($sql);
				$product_list[$key] = $db->fetchRow();
				if(in_array($product_list[$key]['price'],$price)){
					$buy_num = array_count_values($price);
					$product_list[$key]['buy_num'] = $buy_num[$product_list[$key]['price']];
				} else {
					$product_list[$key]['buy_num'] = $product_num[$key] > 0 ? $product_num[$key] : 1;
				}
				$new_seat_com = $new_seat[$product_list[$key]['price']];
				if(!empty($new_seat_com)){

					foreach($new_seat_com as $k => $v){
						$exp = explode(',',$v);
						$product_list[$key]['seat_model_id'][$k] = $exp[0];
						$product_list[$key]['seat_seat_row'][$k] = $exp[1];
						$product_list[$key]['seat_seat_cols'][$k] = $exp[2];
					}

				} else {
					$product_list[$key]['seat_model_id'] = [];
					$product_list[$key]['seat_seat_row'] = [];
					$product_list[$key]['seat_seat_cols'] = [];
				}

				$product_list[$key]['un_seat_model_id'] = serialize($product_list[$key]['seat_model_id']);
				$product_list[$key]['un_seat_seat_row'] = serialize($product_list[$key]['seat_seat_row']);
				$product_list[$key]['un_seat_seat_cols'] = serialize($product_list[$key]['seat_seat_cols']);

				if($product_list[$key]['stock'] <= 0 ){
					unset($product_list[$key]);
				}

				$total_price = $total_price + ($product_list[$key]['price']*$product_list[$key]['buy_num']);
			}

			$tpl->assign('product_list',$product_list);
			$tpl->assign('total_price',$total_price);
			$tpl->assign('spot_id',$spot_id);

			if(empty($product_list)){
				msg($config['weburl']."/index.php","您所下单的票品已售罄了");
				return false;
			}

			//支付方式
			$sql = "select payment_id,payment_name,payment_type,payment_desc from ".PAYMENT." where payment_type!='cards' and active=1 order by payment_id desc";
			$db->query($sql);
			$pay = $db->getRows();
			$tpl->assign("pay",$pay);
			$tpl->assign("consignee",$orderadder->get_consignee());//收货地址

			$cc_sql = "select * from ".CARDCHECK." where uid = '$buid' order by id desc ";
			$db->query($cc_sql);
			$card_check = $db->fetchRow();
			$tpl->assign("card_check",$card_check);

			$sql = "select id,type,title,`desc` from ".LGSTEMP." where status=1"; //配送方式
			$db->query($sql);
			$ship = $db->getRows();
			foreach($ship as $key=>$val)
			{
				$ship[$key]['price']=$logistics->count_freight($val['id'],$city,$sumprice,$weight);
			}
			$tpl->assign("ship",$ship);

			//区域
			$sql = "select * from ".DISTRICT." where pid = 0 ";
			$db->query($sql);
			$prov = $db->getRows();
			$tpl->assign("prov",$prov);

			//取票城市
			$pickup_sql = "select * from ".SINCE." where statu = '1' ";
			$db->query($pickup_sql);
			$pickup_city = $db->getRows();
			$tpl->assign("pickup_city",$pickup_city);


		} else {
			//=============================提交订单
			foreach($_POST as $key => $val){

				if(!is_array($val)){
					$param[$key] = htmlspecialchars(stripslashes($val));
				} else {
					$param[$key] = $val;
				}

			}
			$param['id_card'] = !empty($param['id_card']) ? $param['id_card'] : '';
			$param['student_card'] = !empty($param['student_card']) ? $param['student_card'] : '';
			if(!empty($param['spot_model_id'])){
				foreach($param['spot_model_id'] as $k => $v){
					$param['spot_model_id'][$k] = str_replace('\\','',$v);
					$param['seat_seat_row'][$k] = str_replace('\\','',$param['seat_seat_row'][$k]);
					$param['seat_seat_cols'][$k] = str_replace('\\','',$param['seat_seat_cols'][$k]);
				}
			}
			if($param['delivery_way'] != 'pickup' ){

			if(empty($param['ship_name'])||empty($param['provinceid']) || empty($param['cityid']) || empty($param['areaid']) ||empty($param['ship_mobile']) ||empty($param['ship_addr'])){
				echo "<script type='text/javascript'> alert('请填写地址');window.history.back();window.location.reload();</script>";
				return false;
			}

		} else {


if(empty($param['pick_name'])||empty($param['pick_mobile']) || empty($param['pick_provinceid']) || empty($param['pick_addr']) ){
				echo "<script type='text/javascript'> alert('请填写取票地址');window.history.back();window.location.reload();</script>";
				return false;

			}

		}

			if(empty($param['delivery_way'])){
				echo "<script type='text/javascript'> alert('请选择配送方式');window.history.back();window.location.reload();</script>";
				return false;
			}
			if(empty($param['pay_type'])){
				echo "<script type='text/javascript'> alert('请选择支付方式');window.history.back();window.location.reload();</script>";
				return false;
			}
			if(empty($param['product_id']) || empty($param['num'])){
				echo "<script type='text/javascript'> alert('请选择购买的票品');window.location.href='".$config['weburl']."';</script>";
				return false;
			}
			$product_total_price = 0; //产品总价格
			foreach($param['product_id'] as $key => $val){
				if(empty($param['num'][$key]) || $param['num'][$key] <= 0){
					echo "<script type='text/javascript'> alert('购买的票品数量至少为一张');window.history.back();window.location.reload();</script>";
					return false;
				}
				$db->query("select * from ".SETMEAL." where id='$val' ");
				$product_list[$key] = $db->fetchRow();
				$product_price = $product_list[$key]['price']*$param['num'][$key];
				$product_total_price = $product_total_price + $product_price; //产品总价格
				$db->query("select * from ".PRO." where id='{$product_list[$key]['pid']}' ");
				$products =$db->fetchRow();
			}



			$db->query("select * from ".MEMBERADDR." where name='{$param['ship_name']}' and provinceid='{$param['provinceid']}' and cityid='{$param['cityid']}' and areaid='{$param['areaid']}' and address='{$param['ship_addr']}' and mobile='{$param['ship_mobile']}' ");
			$is_address_exits = $db->fetchRow();
			if(empty($is_address_exits)){
				//新增地址
				$address_sql = "insert into ".MEMBERADDR." (`userid`,`name`,`provinceid`,`cityid`,`areaid`,`address`,`mobile`) VALUES
 				('$buid','{$param['ship_name']}','{$param['provinceid']}','{$param['cityid']}','{$param['areaid']}','{$param['ship_addr']}','{$param['ship_mobile']}')";
				$db->query($address_sql);
			}

			//实名验证
            $cc_sql = "select * from ".CARDCHECK." where uid = '$buid' and real_card_type = '{$param['real_card_type']}' and real_card_no = '{$param['real_card_no']}' ";
			$db->query($cc_sql);
			$card_check = $db->fetchRow();
			if(empty($card_check)){
				$add_time = time();
				$cci_sql = "insert into ".CARDCHECK." (`uid`,`real_user_name`,`real_card_type`,`real_card_no`,`add_at`) VALUES
 				('$buid','{$param['real_user_name']}','{$param['real_card_type']}','{$param['real_card_no']}','$add_time')";
				$db->query($cci_sql);
			}



			//选择配送方式
			$shipping = [];
			if($param['delivery_way'] == 'express'){
				$ship_sql = "select l.*,c.default_price from ".LGSTEMP." l left join ".LGSTEMPCON." c on l.id = c.temp_id where l.type=0";
				$db->query($ship_sql);
				$shipping = $db->fetchRow();
				if($param['provinceid'] == $products['province'] && $param['cityid'] ==$products['city'] ){
					$freight = $shipping['default_price']; //默认 同城
				} elseif($param['provinceid'] == $products['province'] && $param['cityid'] !=$products['city']){
					$freight = 13; //省内
				} elseif($param['provinceid'] != $products['province']){
					$freight = 22; //省外
				} elseif(in_array(['32,33,34'],$param['provinceid'])){
					$freight = 92; // 港澳台
				} else {
					$freight = $shipping['default_price']; //默认 同城
				}

			} else {
				$freight = 0;
				$shipping['title'] = "上门自取";
				$shipping['id'] = 2;
			}

			$cost = round($product_total_price,2);

			if($cost <=0){
				echo "<script type='text/javascript'> alert('支付金额异常');window.history.back();window.location.reload();</script>";
				return false;
			}

			//支付方式
			$sql = "select payment_id,payment_name from ".PAYMENT." where payment_type='{$param['pay_type']}' ";
			$db->query($sql);
			$pay = $db->fetchRow();
			//创建订单
			$order_id=date("Ymdhis").rand(0,9);//订单号
			$pname=!empty($products['pname']) ? $products['pname'] : $config['company'];//此次购物的产品名总称
			$pay_price = ($cost - $param['cost_point']) > 0 ? $cost - $param['cost_point'] : 0;
			/***生成订单****/
			$sql = "INSERT INTO ".ORDER."(member_id,order_id,create_time,payment_id,payment_name,ship_name,ship_addr,ship_mobile,cost,freight,provinceid,cityid,areaid,
			invoice_type,invoice_company,shipping_id,shipping_name,point,id_card,student_card,cost_point,invoice_addr,pick_name,pick_mobile,pick_provinceid,
			pick_addr,real_user_name,real_card_type,real_card_no) VALUES
				($buid,'$order_id','".time()."','{$pay['payment_id']}','{$pay['payment_name']}','{$param['ship_name']}','{$param['ship_addr']}','{$param['ship_mobile']}','$pay_price','$freight','{$param['provinceid']}','{$param['cityid']}',
				'{$param['areaid']}','{$param['invoice_type']}','{$param['invoice_company']}','{$shipping['id']}','{$shipping['title']}','{$products['point']}','{$param['id_card']}','{$param['student_card']}','{$param['cost_point']}',
				'{$param['invoice_addr']}','{$param['pick_name']}','{$param['pick_mobile']}','{$param['pick_provinceid']}','{$param['pick_addr']}','{$param['real_user_name']}',
				'{$param['real_card_type']}','{$param['real_card_no']}')";
			$flag=$db->query($sql);

			//--产品信息
			foreach($product_list as $key=>$val)
			{
				$sql = "INSERT INTO ".ORPRO." (`order_id`,`buyer_id`,`pid`,`pcatid`,`name`,`pic`,`price`,`num`,`time`,`product_id`,`per_date`,spot_id,spot_model_id,seat_seat_row,seat_seat_cols) VALUES ($order_id,$buid,$val[pid],'$val[catid]','$val[pname]','".$val['pic']."','".$val['price']."','".$param['num'][$key]."','".time()."','{$val['id']}','{$val['performance_start_time']}',
				'{$param['spot_id']}','{$param['spot_model_id'][$key]}','{$param['seat_seat_row'][$key]}','{$param['seat_seat_cols'][$key]}')";
				$db->query($sql);
				$pname=$pname.'-'.$val['pname'];
			}
			include_once("$config[webroot]/module/product/includes/plugin_order_class.php");
			include_once("$config[webroot]/module/member/includes/plugin_member_class.php");
			$order=new order();
			$member = new member();
			$order->order_log($order_id,'订单创建','创建');
			$order->add_order_delivery($order_id,$ship,'');
			$order->add_order_payment($order_id,($cost+$freight),$pay);

			$member->add_points(($param['cost_point']*100) * -1, '4', $order_id, $buid);
			include_once("$config[webroot]/module/payment/lang/$config[language].php");
			$post['type']=1;//直接到账
			$post['action']='add';//
			$post['buyer_email']=$buid;
			$post['seller_email']='admin@systerm.com';
			$post['order_id']=$order_id;//外部订单号
			$post['price']=$pay_price + $freight;//订单总价，单价元
			$post['return_url']='main.php?m=product&s=admin_orderdetail&id='.$order_id.'&type=buy';//返回地址
			$post['notify_url']='main.php?m=product&s=admin_orderdetail&id='.$order_id.'&type=buy';//异步返回地址。
			$post['note']=$pname;
			pay_get_url($post);//跳转至订单生成页面
			if($re<0)
			{
				if($re==-2)
					msg('main.php?m=payment&s=admin_info','您的支付账户还没有开通');
				if($re==-1)
					msg("$config[weburl]/?m=product&s=cart",'卖家没有开通支付功能，暂不能购买');
			}

		}



	}
}
//=================================================
$tpl->assign("config",$config);
$tpl->assign("current","product");
include_once("footer.php");

$out=tplfetch("shop_order.htm",$flag,true);	

?>